package saleMarket.dao;

import saleMarket.domain.Communication;
import saleMarket.domain.Customer;
import saleMarket.domain.ShopOwner;
import saleMarket.service.CustomerService;
import saleMarket.service.ShopOwnerService;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeSet;

/**
 * @author 徐元坤 付饶
 * @version 1.0  12-12-2020
 */

public class CommunicationDao {
    private static CommunicationDao communicationDao = new CommunicationDao();
    private CommunicationDao(){}

    public static CommunicationDao getInstance(){return communicationDao;}

    public Collection<Communication> find(int customer_id,int shopOwner_id,Connection conn) throws SQLException{
        Collection<Communication> communications = new ArrayList<>();
        PreparedStatement find_pstmt = conn.prepareStatement("SELECT * FROM communication " +
                "WHERE customer_id=? AND shopOwner_id=? ");
        find_pstmt.setInt(1,customer_id);
        find_pstmt.setInt(2,shopOwner_id);
        ResultSet findAll_resultSet = find_pstmt.executeQuery();
        while (findAll_resultSet.next()){
            String message = findAll_resultSet.getString("message");
            Customer customer = CustomerService.getInstance().find
                    (customer_id);
            ShopOwner shopOwner = ShopOwnerService.getInstance().find
                    (shopOwner_id);
            Communication communication = new Communication(message,customer,shopOwner);
            communications.add(communication);
        }
        return communications;
    }

    public boolean add(Communication communication,Connection conn) throws SQLException{
        PreparedStatement add_pstmt = conn.prepareStatement("INSERT INTO communication" +
                " (message,customer_id,shopOwner_id) VALUES (?,?,?)");
        add_pstmt.setString(1,communication.getMessage());
        add_pstmt.setInt(2,communication.getCustomer().getId());
        add_pstmt.setInt(3,communication.getShopOwner().getId());
        int affectRow = add_pstmt.executeUpdate();
        return affectRow>0;
    }

    public boolean delete(int customer_id,int shopOwner_id,Connection conn) throws SQLException {
        PreparedStatement delete_pstmt = conn.prepareStatement("DELETE FROM communication" +
                " WHERE customer_id=? AND shopOwner_id=?");
        delete_pstmt.setInt(1,customer_id);
        delete_pstmt.setInt(2,shopOwner_id);
        Integer affectRow = delete_pstmt.executeUpdate();
        JdbcHelper.close(delete_pstmt);
        return affectRow>0;
    }

}
